<?php

namespace app\admin\validate;

use think\Validate;

class DbUsercare extends Validate
{
    /**
     * 验证规则
     */
    protected $rule = [
        'account' => 'require|regex:/^[A-Za-z0-9]{4,20}$/|unique_account:account',
        'name'    => 'require',
        'pwd'     => 'require|regex:\S{32}',
        'tel'     => 'regex:/^1[3-9]\d{9}$/|unique_tel:tel'
    ];

    /**
     * 字段描述
     */
    protected $field = [
    ];
    /**
     * 提示消息
     */
    protected $message = [
    ];
    /**
     * 验证场景
     */
    protected $scene = [
        'add'  => ['account', 'name', 'pwd', 'tel'],
        'edit' => ['account', 'name', 'tel'],
    ];

    public function __construct(array $rules = [], $message = [], $field = [])
    {
        $this->field                       = [
            'account' => __('Account'),
            'name'    => __('Name'),
            'pwd'     => __('Pwd'),
            'tel'     => __('Tel')
        ];
        parent::__construct($rules, $message, $field);
    }

    // 验证账号是否存在
    protected function unique_account($value, $rule, $data)
    {
        if(array_key_exists('id',$data)){  //编辑
            $usercare_info = model('DbUsercare')->where('id', $data['id'])->find();
            if ($value != $usercare_info['account']) {
                $res = model('DbUsercare')->where($rule, $value)->where('status', 1)->find();
                if ($res) {
                    return __('Account exist');
                } else {
                    return true;
                }
            }else{
                return true;
            }
        }else{  //添加
            $res = model('DbUsercare')->where($rule, $value)->where('status', 1)->find();
            if ($res) {
                return __('Account exist');
            } else {
                return true;
            }
        }
    }

    // 验证手机号是否存在
    protected function unique_tel($value, $rule, $data)
    {
        if(array_key_exists('id',$data)) {  //编辑
            $usercare_info = model('DbUsercare')->where('id', $data['id'])->find();
            if ($value != $usercare_info['tel']) {
                $res = model('DbUsercare')->where($rule, $value)->where('status', 1)->find();
                if ($res) {
                    return __('Tel exist');
                } else {
                    return true;
                }
            }else{
                return true;
            }
        }else{//添加
            $res = model('DbUsercare')->where($rule, $value)->where('status', 1)->find();
            if ($res) {
                return __('Tel exist');
            } else {
                return true;
            }

        }

    }

}
